package com.zlgs.cqyf.vote;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import weaver.conn.RecordSet;


/**
 * Servlet implementation class AddVoteDataFromBpmServlet
 */
public class AddVoteDataFromBpmServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public AddVoteDataFromBpmServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServ	letRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		JSONObject retObject = new JSONObject();
		PrintWriter writer = response.getWriter();
		try {
			String strUrl1="http://10.125.138.111:8090/201912111250565056_谷李(agul6)_lkq.PNG";
			retObject.put("fileName11",strUrl1.substring(strUrl1.lastIndexOf("/")+1, strUrl1.length()) ) ;
			 String strUrl="http://10.125.138.111:8090/201912111250565056_谷李(agul6)_lkq.PNG";
			String basePath =  request.getRealPath("/");
			String tempPath = "portals"+File.separator+"vote"+File.separator+"pic"+File.separator;
			String serverPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ request.getContextPath();
			//下载文件到指定目录
			String localPath =basePath+tempPath;
			retObject.put("localPath",localPath );
			String fileName= downLoadPic(strUrl, localPath);
			retObject.put("fileName", fileName);
			writer.append( retObject.toString());
		} catch (Exception e) {
			e.printStackTrace();
			retObject.put("sadf", e.getMessage());
		}finally {
		}
		
		
	}

	public boolean checkDateFormat(Object d) {
		try {
			DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDateTime.parse(d.toString(),df);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 开始时间，结束时间校验
	 * 
	 * @param d1
	 * @param d2
	 * @return
	 */
	public boolean checkDateTime(Date d1, Date d2) {
		Calendar startInstance = Calendar.getInstance();
		startInstance.setTime(d1);
		Calendar endInstance = Calendar.getInstance();
		endInstance.setTime(d2);
		if (d1.before(d2)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter printWriter = null;
		JSONObject retObject = new JSONObject();
		try {
			retObject.put("code", 200);
			retObject.put("msg", "success"); 
			
//			  Map<String, String> res = new HashMap<String, String>();
//		        Enumeration<?> temp = request.getParameterNames();
//		        if (null != temp) {
//		            while (temp.hasMoreElements()) {
//		                String en = (String) temp.nextElement();
//		                String value = request.getParameter(en);
//		                res.put(en, value);
//		                //如果字段的值为空，判断若值为空，则删除这个字段>
////		                if (null == res.get(en) || "".equals(res.get(en))) {
////		                    res.remove(en);
////		                }
//		            }
//		        }
//		        retObject.put("msg1231231", res); 
			
			printWriter = response.getWriter();
			Object rewardType = request.getParameter("rewardType"); // 奖项类型
			if (null == rewardType || "".equals(rewardType.toString())) {
				// 终止程序执行-直接finally
				throw new RuntimeException("奖项类型不能为空!");
			}
			Object rewardName = request.getParameter("rewardName"); // 奖项名称
			if (null == rewardName || "".equals(rewardName.toString())) {
				// 终止程序执行-直接finally
				throw new RuntimeException("奖项名称不能为空!");
			}
			Object type = request.getParameter("type"); // 投票类型
			if (null == type) {
				// 终止程序执行-直接finally
				throw new RuntimeException("投票类型不能为空!");
			}
			Object members = request.getParameter("members"); // 团队成员信息不能为空
//			if (type.toString().equals("1") && (null == members || "".equals(members.toString()))) {
//				throw new RuntimeException("团队成员信息不能为空!");
//				// 终止程序执行-直接finally
//			}
			
			StringBuffer  memberNames = new StringBuffer()  ;
			JSONArray memberArray =    JSONArray.parseArray(members.toString());
			Iterator<Object> memberIterator = memberArray.iterator();
			while(memberIterator.hasNext()){
				Object object = memberIterator.next();
				JSONObject memberObject = JSONObject.parseObject(object.toString()) ;
				Object memberName = memberObject.get("name");
				if(null!=memberName){
					memberNames.append(memberName.toString()+",");
				}
			}
			int length = memberNames.length();
			if(length>0){
				memberNames = memberNames.replace(length-1, length, "");
			}
			
			Object nominatorProjectName = null==request.getParameter("nominatorProjectName")?"无":request.getParameter("nominatorProjectName"); // 团队获奖名称不能为空
			Object applicat = null == request.getParameter("applicat")?"无":request.getParameter("applicat");    // 团队获奖名称不能为空
			Object levelFirstDeptName = null == request.getParameter("levelFirstDeptName")?"无":request.getParameter("levelFirstDeptName"); // 申请人一级部门名称
			Object levelSecondDeptName =  null == request.getParameter("levelSecondDeptName")?"无":request.getParameter("levelSecondDeptName");    // 申请人二级部门名称
			Object applicantPosition =  null == request.getParameter("applicantPosition")?"无":request.getParameter("applicantPosition");    // 申请人职位
			 
			Object auditTimeObject = request.getParameter("auditTime"); // BMP审核通过时间，也就是提名信息创建时间
			if (null == auditTimeObject || "".equals(auditTimeObject.toString()) || !checkDateFormat(auditTimeObject.toString())) {
				// 终止程序执行-直接finally
				throw new RuntimeException("BPM审核时间格式错误!");
			}
			Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(auditTimeObject.toString());
			java.sql.Timestamp auditTime =  new Timestamp(date.getTime());
			Object nominatorName = null == request.getParameter("nominatorName")?"无":request.getParameter("nominatorName"); // 被提名人姓名/团队名称
			Object nominatorDetpName = null == request.getParameter("nominatorDetpName")?"无": request.getParameter("nominatorDetpName"); // 被提名人部门/团队部门名称
			Object nominatorPosition = null == request.getParameter("nominatorPosition")?"无":request.getParameter("nominatorPosition"); // 被提名人职位
			Object nominatorPhoto =  null == request.getParameter("nominatorPhoto")?"无": request.getParameter("nominatorPhoto"); // 被提  名人/团队  照片
			Object complete = null == request.getParameter("complete")?"无":request.getParameter("complete"); // 完成了什么
			Object influence = null == request.getParameter("influence")?"无":request.getParameter("influence"); // 成就/影响
			Object isEconomic = null == request.getParameter("isEconomic") || "".equals(request.getParameter("isEconomic")) ?0:request.getParameter("isEconomic") ;  // 是否有经济效益  0：没有，1：有
			Object saveMoney = null ==  request.getParameter("saveMoney") || "".equals(request.getParameter("saveMoney"))?0:request.getParameter("saveMoney"); // 节约金额，单位为元
			Object projectNum = null==request.getParameter("projectNum")?"":request.getParameter("projectNum"); // 项目编号
			Object timeType = null == request.getParameter("type")||"".equals(request.getParameter("type")) ?0:request.getParameter("type"); // 投票时间类型 0：季度  ，1：年度
			Object introduction = null == request.getParameter("introduction")?"":request.getParameter("introduction"); // 提名简介
			Object nominatorSecondDeptName = null == request.getParameter("nominatorSecondDeptName")?"": request.getParameter("nominatorSecondDeptName"); // 提名人二级部门
			Object nominatorType = null == request.getParameter("nominatorType")||"".equals(request.getParameter("nominatorType"))?0: request.getParameter("nominatorType"); // 提名类型
			Object declaration = null ==request.getParameter("declaration")?"无":request.getParameter("declaration"); // 提名宣言
			Object projectGoal = null ==request.getParameter("projectGoal")?"无":request.getParameter("projectGoal"); // 提名宣言
			
			
			String basePath =  request.getRealPath("/");
	    	String tempPath = "portals"+File.separator+"vote"+File.separator+"pic";
	    	if(null == nominatorPhoto && "".equals(nominatorPhoto.toString())) {
	    		throw new RuntimeException("提名照片未传!");
	    	}
	    	//下载文件到指定目录
	    	String fileName= downLoadPic(nominatorPhoto.toString(), basePath+tempPath);
	    	if(!"".equals(fileName)) {
	    		nominatorPhoto = tempPath+File.separator+fileName;
	    	}
			// 接口规范 type 评优类型： 0：季度 ，1：年度  2：专项       兼容表vote_awards 字段 data_type  1 年度 2 季度
			if("0".equals(timeType.toString())){
				timeType = 2;
				rewardType = GetQuarterByDate()+rewardType ;
			}else if("1".equals(timeType.toString()) || "2".equals(timeType.toString())){
				timeType = 1;
				rewardType = GetYearByDate()+rewardType; 
			}
			
			// 提名类型 0 个人  ，1 团队      数据库 ： 1 个人，2团队
			
			if("0".equals(nominatorType)){
				nominatorType = 1;
			}else if("1".equals(nominatorType.toString())){
				nominatorType = 2;
			}
			
			// 第一步先插入 大奖项
//			先根据大奖项信息查询是否存在相同的奖项名称
			String awardId = "";
			RecordSet set0 = new RecordSet();
			set0.executeSql("select top 1 id from vote_awards where name = N'"+rewardType.toString()+"' and is_del = 0 ");
			if(set0.next()){
				awardId = set0.getString("id");
			}
			
			if(null==awardId || "".equals(awardId)){
				// 第一步先插入 大奖项
				String awardBizId = UUID.randomUUID().toString().replace("-", "");
				String insertAwardSql =  "INSERT INTO  vote_awards (name,date_type,create_type,create_time,creator, update_time, updater, is_del,audit_time ,biz_id) values "
						+ "(N'"+rewardType.toString()+"','"+timeType.toString()+"',1,GETDATE(),'BPM', GETDATE() ,'BPM','"+0+"','"+auditTime+"',N'"+awardBizId+"')";
				RecordSet set = new RecordSet();
				set.executeSql(insertAwardSql);
				RecordSet set2 = new RecordSet();
				set2.executeSql("select top 1 * from vote_awards where biz_id =  N'"+awardBizId+"'  ORDER BY id DESC ");
				//只取一条数据 故用if
				if(set2.next()) {
					awardId = set2.getString("id");
				}
			} 
		
			// 第二步先插入 子奖项
//			先根据大奖项信息查询是否存在相同的奖项名称
			String subAwardId = "";
			RecordSet subSet = new RecordSet();
			subSet.executeQuery("select top 1 id from vote_awards_subname where name = N'"+rewardName.toString().trim()+"' and is_del = 0 ");
			if(subSet.next()){
				subAwardId = subSet.getString("id");
			}
			
			if(null==subAwardId || "".equals(subAwardId)){
				String subAwardsBizId = UUID.randomUUID().toString().replace("-", "");
				StringBuffer insertSubAwardSql = new StringBuffer( "INSERT INTO  vote_awards_subname ( name,awards_id,status, msg_status, create_time, creator, is_del,biz_id)");
				insertSubAwardSql.append(" VALUES(N'"+rewardName.toString().trim() +"',"+awardId+",0,0, GETDATE(), N'BPM',0,N'"+subAwardsBizId+"')");
				RecordSet set3 = new RecordSet();
				set3.execute(insertSubAwardSql.toString());
				//根据bizId 查询出子奖项信息
				RecordSet set4 = new RecordSet();
				set4.executeSql("select top 1 * from vote_awards_subname where biz_id = N'"+subAwardsBizId+"' ORDER BY id DESC ");
				if(set4.next()) {
					subAwardId = set4.getString("id");
				};
			}
			// 第三步先插入 提名信息
			String insertNominationSql = "INSERT INTO vote_awards_participator(awards_id, awards_subname_id, member_names,about,declaration,poject_num,applicant_name,applicant_dept_name,applicant_second_dept_name,    applicant_position,nominator_name,        nominator_dept_name ,nominator_project_name,     nominator_second_dept_name,     nominator_position,   nominator_photo,       nominator_type,       win_status, complete,influence,is_economic,save_money,member_json_array, create_time, update_time,project_goal) VALUES(";
			insertNominationSql+=awardId +","+ subAwardId+" , N'"+memberNames.toString()+"',N'"+introduction.toString()+"',N'"+declaration.toString()+"',N'"+projectNum+"',N'"+applicat+"'     ,N'"+levelFirstDeptName+"',N'"+levelSecondDeptName+"' ,N'"+applicantPosition+"',N'"+nominatorName+"',N'"+nominatorDetpName+"' ,N'"+nominatorProjectName+"',N'"+nominatorSecondDeptName+"'   ,N'"+nominatorPosition+"'  ,N'"+nominatorPhoto+"'    ,"+nominatorType+"   ,0       ,N'"+URLDecoder.decode(complete.toString(), "UTF-8")+"'   ,N'"+URLDecoder.decode(influence.toString(), "UTF-8")+"' , "+isEconomic+" ,"+saveMoney+"    ,N'"+members+"' ,GETDATE() ,GETDATE()  ,N'"+URLDecoder.decode(projectGoal.toString(), "UTF-8")+"' )" ;                                
			RecordSet set5 = new RecordSet();
			set5.execute(insertNominationSql);
		} catch (Exception e) {
			e.printStackTrace();
			retObject.put("code", -1);
			retObject.put("msg", e.getMessage());
		} finally {
			printWriter.append(retObject.toString());
		}
		
		
	}
	 
	private  static String GetQuarterByDate() {
		 
		Date now = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(now);
		String year = String.valueOf(calendar.get(Calendar.YEAR));
		int mouth = now.getMonth()+1;
		if(mouth>=1 && mouth<=3){
			return year + "年第一季度";
		}else if(mouth>=4 && mouth<=6){
			return year + "年第二季度";
		}else if(mouth>=7 && mouth<=9){
			return year + "年第三季度";
		}else if(mouth>=10 && mouth<=12){
			return year + "年第四季度";
		}else{
			return "";
		}
	}
	private  static String GetYearByDate() {
		
		Date now = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(now);
		return   String.valueOf(calendar.get(Calendar.YEAR))+"年";
	}

	public  String downLoadPic(String strUrl,String path){
		String retFileName ="";
		  //创建输出流  
		FileOutputStream outStream = null;
		try {
			retFileName = strUrl.substring(strUrl.lastIndexOf("/")+1, strUrl.length());
			File imageFileDir = new File(path);  
			if(!imageFileDir.exists()) {
				imageFileDir.mkdir();
			}
			path = path+File.separator+retFileName;
			File imageFile = new File(path);  
			if(!imageFile.exists()){
				imageFile.createNewFile();
			}
//			String decode = java.net.URLEncoder.encode(strUrl,"utf-8");
			URL url = new URL(urlEncodeChinese(strUrl));
			//new一个URL对象  
			//打开链接  
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
			//设置请求方式为"GET"  
			conn.setRequestMethod("GET");  
			//超时响应时间为5秒  
			conn.setConnectTimeout(10 * 1000);  
			//通过输入流获取图片数据  
			InputStream inStream = conn.getInputStream();  
			//得到图片的二进制数据，以二进制封装得到数据，具有通用性  
			byte[] data = readInputStream(inStream);  
			//new一个文件对象用来保存图片，默认保存当前工程根目录  
			outStream = new FileOutputStream(imageFile);  
			//写入数据  
			outStream.write(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(null!=outStream) {
				//关闭输出流  
				try {
					outStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}  
			}
		}
	 return retFileName;
	}
	
	public static byte[] readInputStream(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        //创建一个Buffer字符串  
        byte[] buffer = new byte[1024];  
        //每次读取的字符串长度，如果为-1，代表全部读取完毕  
        int len = 0;  
        //使用一个输入流从buffer里把数据读取出来  
        while( (len=inStream.read(buffer)) != -1 ){  
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度  
            outStream.write(buffer, 0, len);  
        }  
        //关闭输入流  
        inStream.close();  
        //把outStream里的数据写入内存  
        return outStream.toByteArray();  
    }  
	public static String urlEncodeChinese(String url){
	    String resultURL = "";
	    try {
	        for (int i = 0; i < url.length(); i++) {
	            char charAt = url.charAt(i);
	            //对汉字和空格处理
	            if (isChinese(charAt) || isNbsp(charAt)) {
	                String encode = URLEncoder.encode(charAt+"","UTF-8");
	                resultURL+=encode;
	            }else {
	                resultURL+=charAt;
	            }
	        }
	    } catch (Exception e) {
	       e.printStackTrace();
	    }
	    return resultURL;
	}
	
	
	public static boolean isChinese(char c) {
	    return String.valueOf(c).matches("[\u4e00-\u9fa5]");
	}

	// 判断空格
	public static boolean isNbsp(char c){
	    return String.valueOf(c).matches("\u00A0|\u0020|\u3000");
	}
	public static void main(String[] args) {
	 String dept ="一级-二级-三级";
	 String[] split = dept.split("-");
	 if(split.length>=3){
		 System.out.println(split[0]+"-"+split[1]);
	 }
	 
	}
	
	
	
}
